<template>
  <div class="app-scheduling" style="margin: 0 !important;">
    <el-form :model="productionQuery" :rules="productionrules" ref="productionQuery" label-width="90px" class="demo-ruleForm"
      >
      <el-col class="productionCommon productionCommonCopy">
        <el-form-item label="后台单号">
          <el-input v-model.trim="productionQuery.xmbzNo" clearable placeholder="后台单号" size="small" style="width: 180px;"></el-input>
        </el-form-item>
        <el-form-item label="总仓" label-width="55px">
          <el-select ref="mainWarehouseRef" v-model="productionQuery.mainWarehouse"  placeholder="总仓" size="small" @change="getmainWarehouseIds"
            style="width: 100px;" @keydown.native="selectBlur($event)">
            <el-option v-for="(mainWareHouse,index) in getMainWarehouseList" :key="index" :label="mainWareHouse.deptName"
              :value="mainWareHouse.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分仓" label-width="55px" class="branchWareHouse">
          <el-select ref="barnchWarehousesRef" v-model="productionQuery.warehouseId"  placeholder="分仓" size="small" style="width: 90px;"
            class="branchWareHouse" @change="getbarnchWarehouses" @keydown.native="selectBlur($event)">
            <el-option v-for="item in getSeparateWarehouseList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="蛋糕状态" label-width="79px">
          <el-select ref="statusRef" v-model="productionQuery.status" placeholder="全部" size="small" style="width: 100px;" @keydown.native="selectBlur($event)">
            <el-option v-for="item in statusList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
          </el-select>
        </el-form-item>
        <el-form-item label="打印状态" label-width="79px">
          <el-select ref="printingRef" v-model="productionQuery.printingState" placeholder="全部" size="small" style="width: 100px;" @keydown.native="selectBlur($event)">
            <el-option v-for="item in printingStateList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
          </el-select>
        </el-form-item>
        <el-form-item label="配送时间">
          <el-form-item style="display: flex;">
            <el-date-picker
              v-model="timeValue"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm"
              :default-time="['00:00:00', '23:59:59']"
              format="yyyy-MM-dd HH:mm"
              :clearable="false"
              size="small"
              @change="changeTime"
              align="right">
            </el-date-picker>
          </el-form-item>
        </el-form-item>
        <el-form-item label="产品名称">
          <el-autocomplete
            id="goodsNameRef"
            ref="goodsNameRef"
            v-model="productionQuery.goodsName"
            :fetch-suggestions="querySearch"
            placeholder="产品名称"
            size="small"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="规格">
          <el-input v-model.trim="productionQuery.goodsSpecs" clearable placeholder="产品磅数" size="small" style="width: 100px;"></el-input>
        </el-form-item>
        <el-form-item label-width="20px">
          <el-button icon="el-icon-search" type="primary" size="small" plain @click="submitForm('productionQuery')">查询</el-button>
        </el-form-item>

    <!-- 红黄蓝3块 -->
      <div class="statistics">
        <div class="production-bigbutton primary">
          <el-col class="production-message">今日待生产</el-col>
          <el-col class="production-number">{{ getProductionOrderSummaryList.stayProductionNum }}个</el-col>
        </div>
        <div class="production-bigbutton success">
          <el-col class="production-message">今日生产中</el-col>
          <el-col class="production-number">{{ getProductionOrderSummaryList.startProductionNum }}个</el-col>
        </div>
        <div class="production-bigbutton infostatistics">
          <el-col class="production-message">今日已入库</el-col>
          <el-col class="production-number">{{ getProductionOrderSummaryList.warehousingNum }}个</el-col>
        </div>
        <div class="production-bigbutton c-c5e14a">
          <el-col class="production-message">今日备款</el-col>
          <el-col class="production-number">{{ getProductionOrderSummaryList.provisionNum }}个</el-col>
        </div>
        <div class="production-bigbutton c-7adfd5">
          <el-col class="production-message">今日抵用</el-col>
          <el-col class="production-number">{{ getProductionOrderSummaryList.deductionNum }}个</el-col>
        </div>
        <div class="production-bigbutton c-e64949">
          <el-col class="production-message">今日报损</el-col>
          <el-col class="production-number">{{ getProductionOrderSummaryList.lossNum }}个</el-col>
        </div>
      </div>
      </el-col>
      <!-- </el-col> -->
    </el-form>
    <!-- 批量打印 -->
    <div class="print-box">
      <printForm ref="printForm" v-bind:orderGoodriesList="StampStorageReturnList" id="printForm" :needBlessings="labelchecked" :isOpenPrintPreview="isOpenPrintPreview" @printSuccess="onPrintSuccess" :needIngredient="productionInfoChecked"></printForm>
    </div>
    <!-- 批量生产、打印、入库 -->
    <el-col class="productionCommon">
      <div class="productionBlock">
        <el-col :span="7" style="display: flex;flex-direction: column;align-items: center;" class="button-select">
          <el-button type="primary" size="small" @click="volumnProduction" class="production-button" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}" data-btn-type="print">批量生产</el-button>
        </el-col>
        <el-col :span="7" style="display: flex;flex-direction: column;align-items: center;" class="button-select">
          <el-button type="primary" size="small" @click="volumnStamp" class="production-button" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">批量打印</el-button>
        </el-col>
        <el-col :span="7" style="display: flex;flex-direction: column;align-items: center;" class="button-select">
          <el-button type="primary" size="small" @click="volumnNormalOrder" class="production-button" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">异常订单</el-button>
        </el-col>
        <el-checkbox class = 'button-select'  v-model="labelchecked" label="是否打印祝福语标签纸" border size="small"></el-checkbox>
        <el-checkbox class = 'button-select' v-model="productionInfoChecked" label="是否打印配料表" border size="small"></el-checkbox>
        <el-checkbox class = 'button-select' v-model="clickFramingchecked" label="开启自动刷单" border size="small" @change="clickFraming"></el-checkbox>
        <el-checkbox class = 'button-select' v-model="isOpenPrintPreview" label="开启打印预览" border size="small"></el-checkbox>
        <el-button class= 'button-operation' type="danger" size="small" @click="closeOrder" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">关闭接单</el-button>
        <el-button  class= 'button-operation' type="danger" plain size="small" @click="onOpenCloseOrder" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">接单关闭列表</el-button>
        <el-button  class= 'button-operation' type="primary" plain size="small" @click="onOrderNotice" >订单通知</el-button>
        <el-dialog :visible.sync="productionStampFlag" center :append-to-body="true" :lock-scroll="false" width="35%"
          z-index="2007">
          <div style="width: 100%;">
            <div style="font-size: 17px;margin-left: 5px;">
              是否决定批量打印{{ StampStorageList.length }}个勾选项？
            </div>
          </div>
          <span slot="footer">
            <el-button @click="StampResetForm()">取消</el-button>
            <el-button type="primary" data @click="StampSubmitForm()">确定</el-button>
          </span>
        </el-dialog>
      </div>
    </el-col>

    <!-- 列表模块 -->
    <el-col style="padding-left: 20px;">
      <productionList :productionQuery="productionQuery" @getProductionNumber="getProductionNumber"
        v-bind:productionInfoChecked="productionInfoChecked" v-bind:labelcheckedFlag="labelchecked" :isOpenPrintPreview="isOpenPrintPreview" ref="procedureEdit" @onPrint="handlePrint" :getMainWarehouseList="getMainWarehouseList"></productionList>
    </el-col>

    <closeOrderListDialog ref="closeOrderListDialog"></closeOrderListDialog>
    <orderNoticeDialog ref="orderNoticeDialog" :needIngredient="productionInfoChecked" :cityId="cityId" :needBlessings="labelchecked" :isOpenPrintPreview="isOpenPrintPreview"></orderNoticeDialog>
    <abnormalOrderDialog ref="abnormalOrderDialog" :mainWarehouseId="productionQuery.mainWarehouse" :warehouseId="productionQuery.warehouseId"></abnormalOrderDialog>
  </div>
</template>

<script>
  import {
    // citySelect,
    getMainWarehouseListByRoleIdAll, // 总仓
    getSeparateWarehouseListByRoleIdAll, // 分仓
  } from "@/api/createOrder";
  import {
    getProductionOrderSummary, // 今日生产数量汇总
    batchStartProduction, // 批量生产
    closeOrder, // 关闭订单
  } from '@/api/shop';
  import productionList from './components/production';
  import printForm from "@/views/scheduling/index/cake/components/printForm/index";
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  import orderNoticeDialog from './components/orderNoticeDialog'
  import abnormalOrderDialog from '@/views/scheduling/components/abnormalOrderDialog'
  import closeOrderListDialog from '@/views/scheduling/components/closeOrderListDialog'
  export default {
    components: {
      productionList,
      printForm,
      Pagination,
      orderNoticeDialog,
      abnormalOrderDialog,
      closeOrderListDialog,
      // CookieTemplate
    },
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入制作人'));
        } else {
          this.startruleForm.producer = value.replace(/\s+/g, '');
          callback();
        }
      };
      var validatePass3 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入裱花人'));
        } else {
          this.startruleForm.carver = value.replace(/\s+/g, '');
          callback();
        }
      };
      var validatePass4 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入打包人'));
        } else {
          this.startruleForm.packer = value.replace(/\s+/g, '');
          callback();
        }
      };
      return {
        pagesize: 5,
        currentPage: 1,
        clickFramingchecked: false, // 开启自动刷单
        productionStampFlag: false, // 批量打印
        productionStorageFlag: false, // 批量入库
        productionQuery: {
          deptId: JSON.parse(window.localStorage.getItem("saber-areaId")).content,
          xmbzNo: '',
          mainWarehouse: '', // 总仓
          warehouseId: '', //分仓
          status: 0,
          deliveryStartTime: this.dayjs(
              new Date()
            )
            .format("YYYY-MM-DD 00:00:00")
            .toString(), //配送开始时间,
          deliveryEndTime: this.dayjs(
              new Date()
            )
            .format("YYYY-MM-DD 23:59:59")
            .toString(), //配送开始时间,
          goodsName: '', //产品名称
          goodsSpecs: '', // 产品磅数
          printingState: 0,// 打印状态
          // size: 10
        },
        productionrules: {
          // name: [
          //   { required: true, message: '请输入活动名称', trigger: 'blur' },
          //   { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          // ],
          // region: [
          //   { required: true, message: '请选择活动区域', trigger: 'change' }
          // ],
        },
        // statusList: '',// 状态
        statusList: [{
            dictKey: 0,
            dictValue: '全部'
          },
          {
            dictKey: 2,
            dictValue: '待生产'
          },
          {
            dictKey: 3,
            dictValue: '生产中'
          },
          {
            dictKey: 4,
            dictValue: '已入库'
          },
          {
            dictKey: 5,
            dictValue: '中转中'
          },
          {
            dictKey: 10,
            dictValue: '已退订'
          },
          {
            dictKey: 9,
            dictValue: '改期'
          }
        ],
        printingStateList: [
          {
            dictKey: 0,
            dictValue: '全部'
          },
          {
            dictKey: 1,
            dictValue: '未打印'
          },
          {
            dictKey: 2,
            dictValue: '已打印'
          },
        ],
        pickerOptions:{
          onPick: (obj) => {
            this.pickerMinDate = new Date(obj.minDate).getTime();
          },
          disabledDate:(time)=> {
            if (this.pickerMinDate) {
              const day1 =  31 * 24 * 3600 * 1000
              let maxTime = this.pickerMinDate + day1;
              let minTime = this.pickerMinDate - day1;
              return time.getTime() > maxTime || time.getTime()<minTime
            }
          }
        },
        // pickerOptions: {
        //   shortcuts: [{
        //     text: '最近一周',
        //     onClick(picker) {
        //       const end = new Date();
        //       const start = new Date();
        //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        //       picker.$emit('pick', [start, end]);
        //     }
        //   }, {
        //     text: '最近一个月',
        //     onClick(picker) {
        //       const end = new Date();
        //       const start = new Date();
        //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        //       picker.$emit('pick', [start, end]);
        //     }
        //   }, {
        //     text: '最近三个月',
        //     onClick(picker) {
        //       const end = new Date();
        //       const start = new Date();
        //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        //       picker.$emit('pick', [start, end]);
        //     }
        //   }]
        // },
        startruleForm: { // 开始生产
          producer: '', // 制作人
          carver: '', // 裱花人
          packer: '', // 打包人
          orderIds: [], // 后台单号
          orderDetails: [{
            id: '',
            producer: '',
            carver: '',
            packer: ''
          }],
          orderDetailId: [], // 订单明细id
        },
        startruleForms: { // 开始生产
          orderIds: [], // 后台单号
          orderDetails: []
        },
        startrules: {
          producer: [{
            required: true,
            validator: validatePass,
            trigger: 'change'
          }],
          carver: [{
            required: true,
            validator: validatePass3,
            // message: '请输入裱花人',
            trigger: 'change'
          }],
          packer: [{
            required: true,
            validator: validatePass4,
            // message: '请输入打包人',
            trigger: 'change'
          }]
        },
        StampruleForm: {},
        // 总仓
        wareHouse: {
          parentId: JSON.parse(window.localStorage.getItem("saber-areaId")).content
        },
        getMainWarehouseList: [], //总仓列表
        abbrHouse: { // 分仓
          deptId: 3
        },
        getSeparateWarehouseList: [], //分仓列表
        getProductionOrderSummaryList: '', // 今日生产数量列表
        cityLi: {
          roleId: 1
        },
        batchStartProductionList: { //批量生产请求接口订单列表列表
          orderIds: [],
          orderDetails: []
        },
        orderWarehousingList: {
          orderId: 123,
          orderDetailId: 132
        },
        addOrderWarehousingLog: { // 新增入库记录列表
          orderId: 123,
          orderDetailId: 132,
          warehousingState: 0
        },
        StampStorageList: [], // 打印列表
        StorageRecordStartFlag: false, // 入库成功与否弹框
        StorageRecordList: [], // 获取入库记录请求列表
        StampStorageReturnList: '', //打印返回列表
        StorageRecordAbnormalList: '', // 获取入库记录正常、异常数量
        listProp: {
          deptId: JSON.parse(window.localStorage.getItem("saber-areaId")).content,
          // deptId: 4,
          status: 0,
          size: 100
        },
        closeOrderlist: {
          // deptId: JSON.parse(window.localStorage.getItem("saber-areaId")).content,
          orderDetailIds: [],
          warehouseId: ''
        },
        statusArray: [],
        clickfarmingTimer: null, // 开启接单定时器
        farmingTimer: null, // 异常列表定时器
        cityId: '',
        timeValue: [], // 查询时间值
        timeValueFlag: false, // 查询时间是否大于31天标记
        labelchecked: false, // 打印标签纸开关checked
        productionInfoChecked: false, // 打印生产
        tradeNameRecord: [],// 商品名称历史记录列表
        tradeName: '',
        isOpenPrintPreview: false,
      }
    },
    created() {
      window.addEventListener("keydown",this.keyupEnter);
    },
    watch: {
      'labelchecked'() {
        window.localStorage.setItem('labelchecked',this.labelchecked);
      },
      'closeOrderListOpenFlag'() {
        if(this.closeOrderListOpenFlag) {
          window.removeEventListener("keydown",this.keyupEnter);
        } else {
          window.addEventListener("keydown",this.keyupEnter);
        }
      },
      'productionInfoChecked'() {
        window.localStorage.setItem('productionInfoChecked',this.productionInfoChecked);
      },
      'productionStampFlag'() {
        if(this.productionStampFlag) {
          window.removeEventListener("keydown",this.keyupEnter);
        } else {
          window.addEventListener("keydown",this.keyupEnter);
        }
      },
      'abnormalOrderFlag'() {
        if(this.abnormalOrderFlag) {
          window.removeEventListener("keydown",this.keyupEnter);
        } else {
          window.addEventListener("keydown",this.keyupEnter);
        }
      }
    },
    mounted() {
      window.clearInterval(this.clickfarmingTimer)
      this.getMinWareList();
      this.barnchWarehouses();
      // this.abmormalOrderRecord()
      setTimeout(() => {
        this.cityId = JSON.parse(window.localStorage.getItem("saber-areaId")).content
        this.getDeliveryTime()
        this.getProductionNumber()
      },1000)
      if(window.localStorage.getItem('labelchecked') !== null) {
        if(window.localStorage.getItem('labelchecked') !== undefined && window.localStorage.getItem('labelchecked') !== '') {
          this.labelchecked = JSON.parse(window.localStorage.getItem('labelchecked'));
        } else {
          this.labelchecked = false;
        }
      }
      if(window.localStorage.getItem('productionInfoChecked') !== null) {
        if(window.localStorage.getItem('productionInfoChecked') !== undefined && window.localStorage.getItem('productionInfoChecked') !== '') {
          this.productionInfoChecked = JSON.parse(window.localStorage.getItem('productionInfoChecked'));
        } else {
          this.productionInfoChecked = false;
        }
      }
      // 产品名称搜索记录
      let tradeNameRecord = JSON.parse(window.localStorage.getItem('tradeNameRecord'));
      if(tradeNameRecord === null) {
        this.tradeNameRecord = [];
        window.localStorage.setItem('tradeNameRecord',JSON.stringify(this.tradeNameRecord));
      } else {
        if(tradeNameRecord.length == 0) {
          this.tradeNameRecord = [];
          window.localStorage.setItem('tradeNameRecord',JSON.stringify(this.tradeNameRecord));
        } else {
          this.tradeNameRecord = tradeNameRecord;
        }
      }
      window['ProsubmitForm'] = () => {
        this.submitForm()
      }
      window['ProPrintFlag'] = () => {
        this.$refs['procedureEdit'].StampStoragebtn = false;
        this.$refs['procedureEdit'].Ingredientsbtn = false;
      }
    },
    methods: {
      getMinWareList(){
        this.cityId = JSON.parse(window.localStorage.getItem("saber-areaId")).content
        // console.log('this.cityId',this.cityId)
        // 总仓
        this.wareHouse.parentId = this.cityId;
        getMainWarehouseListByRoleIdAll(this.wareHouse).then(res => {
          res.data.data.unshift({
            id: '',
            deptName: "全部"
          })
          this.getMainWarehouseList = res.data.data
          this.productionQuery.mainWarehouse = res.data.data[0].id;

        })
      },
      //仓库地区ID选择事件
      getmainWarehouseIds(data) {
        this.productionQuery.warehouseId = "";
        this.barnchWarehouses();
      },
      barnchWarehouses() {
          var saberareaIds = JSON.parse(localStorage.getItem("saber-areaId"));
          this.cityareaId = saberareaIds["content"];
          getSeparateWarehouseListByRoleIdAll({
            cityId: this.cityareaId,
            deptId: this.productionQuery.mainWarehouse,
          }).then(response => {
            response.data.data.unshift({
              id: '',
              name: "全部"
            })
            this.getSeparateWarehouseList = response.data.data;
            this.productionQuery.warehouseId = response.data.data[0].id;

          });
      },
      getbarnchWarehouses(data) {
      },
      // 初始页currentPage、初始每页数据数pagesize和数据data
      handleSizeChange: function(size) {
        this.pagesize = size
      },
      handleCurrentChange: function(currentPage) {
        this.currentPage = currentPage
      },
      
      // 计算时间差
      getNowTime() {
        let nowYear = new Date().getFullYear()
        let nowMonth = (new Date().getMonth() + 1) < 10 ? "0" + (new Date().getMonth() + 1) : (new Date().getMonth() +
          1);
        let nowDate = new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate();
        // let nowHours = new Date().getHours() < 10? "0" + new Date().getHours() : new Date().getHours();
        // let nowMinutes = new Date().getMinutes() < 10? "0" + new Date().getMinutes() : new Date().getMinutes();
        // console.log(e.currentTarget.dataset.time,nowYear + '-' + nowMonth + '-' + nowDate + ' ' + nowHours + ':' + nowMinutes)
        let nowTime = nowYear + '-' + nowMonth + '-' + nowDate + ' '
        // console.log('nowTime',nowTime,'nowTime')
        return nowTime
      },
      getSummaryParams() {
        const mainWarehouse = this.getMainWarehouse()
        const params = {
          deptId: this.productionQuery.deptId,
          xmbzNo: this.productionQuery.xmbzNo,
          mainWarehouse:mainWarehouse.deptName === '全部' ? '' : mainWarehouse.deptName,
          warehouseId: this.productionQuery.warehouseId,
          status: this.productionQuery.status,
          deliveryStartTime: this.productionQuery.deliveryStartTime,
          deliveryEndTime: this.productionQuery.deliveryEndTime,
          goodsName: this.productionQuery.goodsName,
          goodsSpecs: this.productionQuery.goodsSpecs
        }
        return params
      },
      getProductionNumber() {
        // 今日生产数量汇总
        const params = this.getSummaryParams()
        getProductionOrderSummary(params).then(res => {
          this.getProductionOrderSummaryList = res.data.data;
        })
      },
      getMainWarehouse() {
        const select = this.getMainWarehouseList.find(item => {
          return item.id === this.productionQuery.mainWarehouse
        })
        return select
      },
      getOrderListParams() {
        const mainWarehouse = this.getMainWarehouse()
        const params = {
          deptId: this.productionQuery.deptId,
          xmbzNo: this.productionQuery.xmbzNo,
          mainWarehouse:mainWarehouse.deptName === '全部' ? '' : mainWarehouse.deptName,
          warehouseId: this.productionQuery.warehouseId,
          status: this.productionQuery.status,
          deliveryStartTime: this.productionQuery.deliveryStartTime,
          deliveryEndTime: this.productionQuery.deliveryEndTime,
          goodsName: this.productionQuery.goodsName,
          goodsSpecs: this.productionQuery.goodsSpecs,
          printingState: this.productionQuery.printingState,
          page: this.productionQuery.page,
          size: this.productionQuery.size
        }
        return params
      },
      // 接单查询（当所需查询参数其中任何一项不为空）
      queryList() {
        this.$refs['procedureEdit'].getList()
      },
      // 查询中是否含有参数
      isQuery() {
        if (this.productionQuery.xmbzNo !== '' ||
            this.productionQuery.mainWarehouse !== '' ||
            this.productionQuery.branchWarehouse !== '' ||
            this.productionQuery.deliveryStartTime !== '' ||
            this.productionQuery.deliveryEndTime !== '' ||
            this.productionQuery.goodsName !== '' ||
            this.productionQuery.goodsSpecs !== '') {
          this.queryList()
        }
      },
      clickFraming(val) { // 刷单
        window.clearInterval(this.clickfarmingTimer)
        if (val == true) {
          this.isQuery()
          this.clickfarmingTimer = setInterval(() => {
            this.isQuery()
          }, 60 * 1000)
        } else {
          window.clearInterval(this.clickfarmingTimer)
          // console.log('停止定时器')
        }
      },
      submitForm(formName) { // 查询
        this.productionQuery.page = this.$refs['procedureEdit'].currentPage - 1;
        this.$refs.abnormalOrderDialog && this.$refs.abnormalOrderDialog.getAbnormalList();
        if(this.tradeNameRecord.length < 8 && (this.productionQuery.goodsName !== '')) {
          this.tradeNameRecord.unshift({'value': this.productionQuery.goodsName});
          window.localStorage.setItem('tradeNameRecord',JSON.stringify(this.tradeNameRecord));
        } else if (this.tradeNameRecord.length >= 8 && (this.productionQuery.goodsName !== '')) {
          this.tradeNameRecord.unshift({'value': this.productionQuery.goodsName});
          this.tradeNameRecord = this.tradeNameRecord.slice(0,8);
          window.localStorage.setItem('tradeNameRecord',JSON.stringify(this.tradeNameRecord));
        }
        this.isgreaterThan(this.productionQuery.deliveryStartTime,this.productionQuery.deliveryEndTime)
        if(!this.timeValueFlag) {
          this.queryList()
          this.getProductionNumber();
        }
        this.$refs['procedureEdit'].StampStoragebtn = false;
        this.$refs['procedureEdit'].Ingredientsbtn = false;
        this.$refs['procedureEdit'].changeCurrentPage()
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      volumnProduction() { // 批量生产
        let oldProcedure = this.$refs['procedureEdit'].getChecked() || [];
        // console.log('this.$refs.getChecked()',oldProcedure)
        this.statusArray = [];
        let productionorderIdList = [];
        let orderNumArr = [];
        let orderNumObj = {};
        orderNumObj = {
          id: '',
          producer: '',
          carver: '',
          packer: ''
        }
        if (oldProcedure.length > 0) {
          oldProcedure.forEach((item, index) => {
            this.statusArray.push(item.productionState)
            orderNumObj = {
              id: oldProcedure[index].id,
              producer: '未填写',
              carver: '未填写',
              packer: '未填写'
            }
            productionorderIdList.push(item.orderId)
            orderNumArr.push(orderNumObj)
          })
          this.startruleForm.orderIds = productionorderIdList
          this.startruleForm.orderDetails = orderNumArr
          this.startruleForms.orderDetails = this.startruleForm.orderDetails
          this.startruleForms.orderIds = this.startruleForm.orderIds
          // console.log(this.startruleForms)
          if (this.statusArray.indexOf(0) > -1 || this.statusArray.indexOf(3) > -1 || this.statusArray.indexOf(4) > -1 ||
            this.statusArray.indexOf(9) > -1 || this.statusArray.indexOf(10) > -1) {
            this.$message({
              message: '点击批量生产前，请选择待生产的蛋糕',
              type: 'warning'
            });
            this.statusArray = []
          } else {
            batchStartProduction(this.startruleForms).then(res => {
              if (res.data.code == 200) {
                this.$notify({
                  title: '批量生产成功',
                  message: '请您耐心等待',
                  type: 'success'
                })
                this.$refs.procedureEdit.checkedAll = false
                this.getProductionNumber()
                this.queryList()
                setTimeout(() => {
                  this.statusArray = []
                }, 1 * 1000);
              }
            })
          }
        } else {
          this.$message({
            message: '您还未选择蛋糕，请先勾选蛋糕',
            type: 'warning'
          });
        }
      },
      startSubmitForm(formName) { // 批量生产确认按钮
        this.startruleForm.orderDetails.forEach(item => {
          item.producer = this.startruleForm.producer
          item.carver = this.startruleForm.carver
          item.packer = this.startruleForm.packer
        })
        this.startruleForms.orderDetails = this.startruleForm.orderDetails
        this.startruleForms.orderIds = this.startruleForm.orderIds
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let startruleForms = this.startruleForms
            batchStartProduction(startruleForms).then(res => {
              if (res.data.code == 200) {
                this.$notify({
                  title: '批量生产成功',
                  message: '请您耐心等待',
                  type: 'success'
                })
                this.$refs[formName].resetFields();
                this.$refs.procedureEdit.checkedAll = false;
                this.getProductionNumber()
                this.queryList()
                setTimeout(() => {
                  this.statusArray = []
                }, 1 * 1000);
              }
            })
          } else {
            return false;
          }
        });
      },
      volumnStamp() { // 批量打印
        window.localStorage.setItem('proPathFlag',this.$route.path);
        let oldProcedure = this.$refs['procedureEdit'].getChecked() || [];
        console.log(oldProcedure)
        if (oldProcedure.length > 0) {
          this.StampStorageList = oldProcedure;
          if (oldProcedure.some(item => Number(item.productionState) !== 3 && Number(item.productionState) !== 4)) {
            this.$message({
              message: '打印失败，只能打印生产中和已入库的蛋糕',
              type: 'warning'
            });
          } else {
            this.productionStampFlag = true;
          }
        } else {
          this.$message({
            message: '您还未选择蛋糕，请先选择蛋糕',
            type: 'warning'
          });
        }
      },
      StampSubmitForm() { // 打印确认按钮
        this.$refs.printForm.callPrint(this.StampStorageList, 1000)
        this.productionStampFlag = false;
      
      },
      handlePrint(StampStorageList) {
        this.$refs.printForm.callPrint(StampStorageList, 1000)
      },
      onPrintSuccess() {
        this.$refs['procedureEdit'].getList();
      },
      getNoProdOrders(orderList) {
        if (orderList && orderList.length) {
          const noProductions = orderList.filter(item => !item.goodsSkuProductions || !item.goodsSkuProductions.length)
          if (noProductions) {
             return noProductions
          }
        }
      },
      StampResetForm() { // 打印取消按钮
        this.productionStampFlag = false
      },
      loading(isLoading) {
        if (isLoading) {
          this.loadingInstance = this.$loading({
            lock: true,
            text: '请求打印中，请稍等...',
          });
        } else {
          this.loadingInstance && this.loadingInstance.close()
        }
      },
      acTiveArrStringFun(obj) {
        var arr = [];
        if (obj != null && obj.length != 0) {
          for (var i = 0; i < obj.length; i++) {
            arr.push(obj[i]);
          }
        }
        return arr.toString();
      },
      StorageRecordSubmitForm() { // 入库信息显示确定按钮
        this.abnormalOrderFlag = false
      },
      // StorageRecordResetForm() { // 入库信息显示取消按钮  getNotReadOrderNewsLogList
      //   this.StorageRecordStartFlag = false
      // }
      abnormalClick() { // 异常订单
        this.abnormalOrderFlag = true;
        this.getAbnormalList() // 异常订单记录
      },
      volumnNormalOrder() {
        this.$refs.abnormalOrderDialog.show()
      },
      // 关闭接单
      closeOrder() {
        let status = []
        let orderDetailIds = []
        let oldProcedure = this.$refs['procedureEdit'].getChecked() || [];
        if (oldProcedure.length > 0) {
          // this.closeOrderFlag = false;
          // let warehouseIds = []
          // console.log('oldProcedure',oldProcedure)
          oldProcedure.forEach((item) => {
            orderDetailIds.push(item.id)
            status.push(item.productionState)
            this.closeOrderlist.warehouseId = item.warehouseId
          })
          this.closeOrderlist.orderDetailIds = orderDetailIds
          // this.closeOrderlist.warehouseIds = warehouseIds
          // this.startruleForm.orderIds = productionorderIdList
          // console.log(this.closeOrderlist, 'this.closeOrderlist',status.indexOf(2))
          if (status.indexOf(12) == -1 && status.indexOf(3) == -1 && status.indexOf(4) == -1 && status.indexOf(9) == -1 &&
            status.indexOf(10) == -1 && status.indexOf(6) == -1 && status.indexOf(2) > -1) {
            // console.log('没有')
            // console.log(this.closeOrderlist.orderDetailIds, 'this.closeOrderlist.orderDetailIds')
            let _this = this;
            window.removeEventListener("keydown",this.keyupEnter);
            this.$confirm('<div">1.关闭后，列表里此规格蛋糕全部下架，是否确认关闭?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><br/><div>2.关闭后，此蛋糕对应的订单会消失，需要客服重新确认！</div>', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              center: true,
              type: 'warning',
              beforeClose(action,instance,done){
                if(action=="confirm"){
                  instance.$refs['confirm'].$el.onclick=function(e){
                    e=e||window.event
                    // console.log(e.detail)
                    if(e.detail!=0){
                      done()
                    }
                  }
                }else{
                  window.addEventListener("keydown",_this.keyupEnter);
                  done()
                }
            }
            }).then(() => {
              closeOrder(this.closeOrderlist).then(res => {
                if (res.data.code == 200) {
                  this.$message({
                    type: 'success',
                    message: '关闭成功!'
                  });
                  this.getProductionNumber()
                  this.queryList();
                  window.addEventListener("keydown",_this.keyupEnter);
                }
              })
            }).catch(() => {
              window.addEventListener("keydown",this.keyupEnter);
              this.$message({
                type: 'info',
                message: '已取消关闭蛋糕'
              });
              this.closeOrderlist.orderDetailIds = [];
              this.closeOrderlist.warehouseId = '';
            });
          } else {
            this.$message({
              message: '所选蛋糕中含有除待生产状态以外的蛋糕，请重新选择蛋糕',
              type: 'warning'
            })
          }
        } else {
          this.$message({
            message: '您还未选择蛋糕，请先选择蛋糕',
            type: 'warning'
          });
          // this.closeOrderFlag = true;
        }
      },
      
      // 获取请求接单关闭列表的分仓id
      getwarehouseId(e) {
        this.getCloseOrderList.warehouseId = e.currentTarget.dataset.id
        // console.log(e.currentTarget.dataset)
      },
      // 设置默认查询日期
      getDeliveryTime() {
        //前一天设定的日期时间
        let d = new Date
        let year1,month1,day1
        [year1,month1,day1] = [d.getFullYear(),d.getMonth(),d.getDate()];
        let date1 = new Date(year1,month1,day1,0);
        let nowMonth1 = (new Date().getMonth() + 1) < 10 ? "0" + (new Date().getMonth() + 1) : (new Date().getMonth() +
          1);
        let nowDate1 = new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate();
        let deliveryStartTime = date1.getFullYear() + '-' + nowMonth1 + '-' + nowDate1 + ' ' + '00:00:00';
        this.timeValue.unshift(date1);
        this.productionQuery.deliveryStartTime = deliveryStartTime;
        //当前设定的日期时间
        let date2 = new Date(year1, month1, day1,23,59,59);
        let deliveryEndTime = date1.getFullYear() + '-' + nowMonth1 + '-' + nowDate1 + ' ' + '23:59:59';
        this.timeValue.push(date2);
        this.productionQuery.deliveryEndTime = deliveryEndTime;
      },
      changeTime(val) {
        this.productionQuery.deliveryStartTime = val[0] + ':00';
        this.productionQuery.deliveryEndTime = val[1] + ':59';
      },
      // 判断是否大于31天
      isgreaterThan(time1,time2) {
        var data1 = Date.parse(time1.replace(/-/g,"/"));
        var data2 = Date.parse(time2.replace(/-/g,"/"));
        var datadiff = data2-data1;
        var time = 31*24*60*60*1000;
        if(time1.length>0 && time2.length>0){
          if(datadiff<0||datadiff>time){
            // console.log("开始时间应小于结束时间并且间隔小于31天，请检查!",data1,data2,datadiff);
            this.$message.warning("时间间隔不可超过31天");
            return this.timeValueFlag = true;
          } else {
            return this.timeValueFlag = false;
          }
        }
      },
      // 回车事件
      keyupEnter(){
        if(window.event.keyCode == 13 ){
          // this.$refs['typeRef'].blur();
          this.submitForm();// 查询事件
        }
      },
      // 选择框回车失焦
      selectBlur(e) {
        if(e.keyCode == 13) {
          this.$refs['mainWarehouseRef'].blur();
          this.$refs['barnchWarehousesRef'].blur();
          this.$refs['statusRef'].blur();
          this.$refs['printingRef'].blur();
          e.returnValue = false;
        }
      },
      // 静止输入空格
      keydown(event) {
        if(event.keyCode == 32) {
          event.returnValue = false;
        }
        if(event.keyCode == 13) {
          this.$refs['goodsNameRef'].blur();
          event.returnValue = false;
        }
      },
      querySearch(queryString, cb) {
        this.tradeNameRecord.forEach((item,index) => {
          if(typeof(item) == 'string') this.tradeNameRecord[index] = { 'value' : item };
        })
        window.localStorage.setItem('tradeNameRecord',JSON.stringify(this.tradeNameRecord));
        let restaurants = this.tradeNameRecord;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      onOrderNotice() {
        this.$refs.orderNoticeDialog.show(this.cityId)
      },
      onOpenCloseOrder() {
        this.$refs.closeOrderListDialog.show()
      }
    },
    destroyed() {
      window.removeEventListener("keydown",this.keyupEnter);
      // window.clearInterval(this.farmingTimer)
      // clearTimeout(this.farmingTimer);
    },
    //如果页面有keep-alive缓存功能，这个函数会触发
    activated() {
      window.addEventListener("keydown",this.keyupEnter);
    },
    deactivated() {
      window.removeEventListener("keydown",this.keyupEnter);
    }
  }
</script>

<style lang="scss" scoped>
  .tablist {
    display: flex;
    margin-bottom: 20px;

    .name {
      padding: 0 20px;
      text-align: center;
      color: #000;
      font-size: 20px;
      line-height: 40px;
      cursor: pointer;

      &.active {
        font-size: 20px;
        color: #43a0ff;
        border-bottom: 1px solid #43a0ff;
      }
    }
  }

  .Abnormalrecord-inline {
    .el-form-item__content {
      line-height: 32px !important;
    }
  }

  .productionCommon {
    display: flex;
    // position: relative;
    // top: 0;
    // left: 0;
    // height: ;
    .productionBlock{
      position: absolute;
      width: 35%;
      // height: 0;
      margin-left: 150px;
      display: flex;
      .button-select{
        margin: 0 5px;
      }
      .button-operation{
        height: 32px;
      }
      // align-items: center;
    }
  }

  .productionCommonCopy {
    display: flex;
    flex-wrap: wrap;
    position: relative;
    .el-form-item{
      margin-bottom: 10px;
    }
  }

  .production-button {
    // margin-top: 30px;
  }

  .production-message {
    font-size: 14px
  }

  .production-number {
    font-size: 16px
  }

  .statistics {
    margin: -10px 0 0 30px;
    // position: relative;
    // left: 0;
    // top: 60px;
    .production-bigbutton {
      margin-right: 20px;
      color: #FFF;
      background-color: #409EFF;
      border-color: #409EFF;
      padding: 5px;
      font-size: 14px;
      border-radius: 4px;
      text-align: center;
      font-weight: 500;
      display: inline-block;
      line-height: 1;
      white-space: nowrap;

      &.success {
        background-color: #67c23a;
        border-color: #67c23a;
      }

      &.infostatistics {
        background-color: #909399;
        border-color: #909399;
      }

      &.c-c5e14a {
        background-color: #c5e14a;
        border-color: #c5e14a;
      }

      &.c-7adfd5 {
        background-color: #7adfd5;
        border-color: #7adfd5;
      }

      &.c-e64949 {
        background-color: #e64949;
        border-color: #e64949;
      }

    }
  }

  .CoummonFlag {
    margin-top: 5px;
    font-size: 12px;
    color: red;
  }

  .el-scrollbar {
    padding-bottom: 15px;
  }

  .StorageRecording-abnormal {
    display: flex;
    justify-content: space-around;
    line-height: 3;
    margin-bottom: 10px;
  }

  .StorageRecording-abnormal span {
    text-align: center;
  }

  .StorageRecord-message {
    color: red;
  }

  .StorageRecord-title {
    color: #454649;
    font-size: 17px;
  }

  .cakeName {
    width: 20%;
    text-align: center;
  }

  .page-component__scroll .el-scrollbar__bar.is-vertical {
    opacity: 0;
  }

  .page-component__scroll .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  #pdf-viewer #content {
    height: 350px !important;
    position: fixed;
    width: 100%;
    z-index: 1;
  }

  .ordermain {
    font-size: 10px;
    line-height: .8;
  }

  .StorageRecord-operation {
    width: 40%;
    text-align: center;
    display: flex;
    justify-content: center;
  }

  .StorageRecord-order {
    width: 20%;
    text-align: center;
  }

  .StorageRecord-record {
    width: 10%;
    text-align: center;
  }

  .StorageRecord-schedule {
    width: 10%;
    text-align: center;
  }

  .branchWareHouse .el-select-dropdown__item {
    padding: 0;
  }

  .print-box {
    position: fixed;
    top: -100%;
    right: -100%;
  }
  .el-date-range-picker .el-picker-panel__footer .el-button--text span {
    display: none;
  }
</style>
